import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class GameMain extends JPanel implements Runnable
{
/**
	 * 
	 */
	private static final long serialVersionUID = 6287085399839229107L;

public static GameMain instance = null;	

private Thread animator;

private boolean running = false;

private BufferedImage dbImage;

private Graphics2D dbg;

public int FPS,SFPS;

public int fpscount;

Random rnd = new Random();

public static GCanvas TelaAtiva = null;

public static TileMap mapa = null;

public GameMain()
{
	System.out.println("Entrou construtor");
	instance = this;
	
	setBackground(Color.white);
	setPreferredSize( new Dimension(Constantes.TELA_LARGURA, Constantes.TELA_ALTURA));

	// create game components
	setFocusable(true);

	requestFocus(); // JPanel now receives key events
	
	if (dbImage == null){
		dbImage = new BufferedImage(Constantes.TELA_LARGURA, Constantes.TELA_ALTURA,BufferedImage.TYPE_INT_ARGB);
		if (dbImage == null) {
			System.out.println("dbImage is null");
			return;
		}else{
			System.out.println("dbImage is not null");
			dbg = (Graphics2D)dbImage.getGraphics();
		}
	}	
	
	
	// Adiciona um Key Listner
	addKeyListener( new KeyAdapter() {
		public void keyPressed(KeyEvent e)
			{ 
				if(TelaAtiva!=null)
				TelaAtiva.tratadorKeyPressed(e);	
			}
		@Override
			public void keyReleased(KeyEvent e ) {
				if(TelaAtiva!=null)
				TelaAtiva.tratadorKeyReleased(e);
			}
	});
	
	addMouseMotionListener(new MouseMotionListener() {
		
		@Override
		public void mouseMoved(MouseEvent e) {
			// TODO Auto-generated method stub
			if(TelaAtiva!=null)
			TelaAtiva.tratadorMouseMoved(e);
		}
		
		@Override
		public void mouseDragged(MouseEvent e) {
			// TODO Auto-generated method stub
			if(TelaAtiva!=null)
			TelaAtiva.tratadorMouseDragged(e);
		}
	});
	
	addMouseListener(new MouseListener() {
		
		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub
			if(TelaAtiva!=null)
			TelaAtiva.tratadorMouseReleased(e);
		}
		
		@Override
		
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			if(TelaAtiva!=null)
			TelaAtiva.tratadorMousePressed(e);
		}
		
		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void mouseClicked(MouseEvent e) {
			// TODO Auto-generated method stub
			if(TelaAtiva!=null)
			TelaAtiva.tratadorMouseClicked(e);
		}
	});
	System.out.println("Saiu construtor");
} // end of constructor GameMain()

public static void TrocaTelaAtiva(GCanvas canvas){
	TelaAtiva = canvas;
}

public void addNotify()
{
	super.addNotify(); // creates the peer
	startGame(); // start the thread
}

private void startGame()
// initialise and start the thread
{
	System.out.println(" entrou start game");
	TelaAtiva = new CanvasPrincipal();
	
	if (animator == null || !running) {
		animator = new Thread(this);
		animator.start();
	}
	System.out.println("start game");
	
} // end of startGame()

public void stopGame()
// called by the user to stop execution
{ System.out.println("stop game");
	running = false; }


public void run()
/* Repeatedly update, render, sleep */
{
	
	running = true;
	
	long DifTime,TempoAnterior;
	
	int segundo = 0;
	DifTime = 0;
	TempoAnterior = System.currentTimeMillis();
	
	while(running) {
//		System.out.println("Running");
	
		if(TelaAtiva!=null){
			TelaAtiva.simulaSe(DifTime);
//			System.out.println("simulou");
			TelaAtiva.desenhaSe(dbg);
//			System.out.println("desenhou");
		}
		paintImmediately(0, 0, Constantes.TELA_LARGURA, Constantes.TELA_ALTURA); // paint with the buffer
	
		try {
			Thread.sleep(3); // sleep a bit
		}	
		catch(InterruptedException ex){}
		
		DifTime = System.currentTimeMillis() - TempoAnterior;
		TempoAnterior = System.currentTimeMillis();
		
		if(segundo!=((int)(TempoAnterior/1000))){
			FPS = SFPS;
			SFPS = 1;
			segundo = ((int)(TempoAnterior/1000));
		}else{
			SFPS++;
		}
	
	}
System.exit(0); // so enclosing JFrame/JApplet exits
} // end of run()

public void paintComponent(Graphics g)
{
	super.paintComponent(g);
	if (dbImage != null){
		g.drawImage(dbImage, 0, 0, null);
	}
}

public static void main(String args[])
{
	GameMain ttPanel = new GameMain();
	System.out.println("1");
  // create a JFrame to hold the timer test JPanel
  JFrame app = new JFrame("RTS");
  System.out.println("2");
  app.getContentPane().add(ttPanel, BorderLayout.CENTER);
  System.out.println("3");
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  System.out.println("4");

  app.pack();
  app.setResizable(false);  
  app.setVisible(true);
} // end of main()

public BufferedImage AbreImagem(String path){
	BufferedImage image = null;
	try {
		BufferedImage imgtmp = ImageIO.read( getClass().getResource(path) );
		image = new BufferedImage(imgtmp.getWidth(), imgtmp.getHeight(), BufferedImage.TYPE_INT_ARGB);
		image.getGraphics().drawImage(imgtmp, 0,0,null);
		imgtmp = null;
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	return image;
}

} // end of GamePanel class
